<script lang="ts" setup>
import { ref } from 'vue'
import { fetchGetUploadKey } from '@/api/upload'
import * as qiniu from 'qiniu-js'
import { UploadFilled } from '@element-plus/icons-vue'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { ElMessage, ElMessageBox, genFileId } from 'element-plus'

// setting 页面是否显示
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  type: {
    type: String,
    default: 'file'
  }
});
const emit = defineEmits(["fileUrl"]);

const upload = ref<UploadInstance>()
// 七牛云上传——————————————————————————————————————————————————
const actionUrl = 'rs-z2.qiniuapi.com' // 这是根据你创建空间时所选择的地区
const imgUrl = ref('')
// 上传文件到七牛云
const uploadQiniu = (req: { file: File; }) => {
  // 重命名要上传的文件
  const keyname = Date.parse(String(new Date())) + Math.floor(Math.random() * 100) + '-' + req.file.name
  // 从后端获取上传凭证token
  fetchGetUploadKey().then((res: any) => {
    let putExtra = {}
    const config = {
      useCdnDomain: true,
      region: qiniu.region.z2
    };
    const observable = qiniu.upload(req.file, keyname, res.token, putExtra, config)
    const observer = {
      next(_res: any) {
        // ...
      },
      error(_err: any) {
        // ...
      },
      complete(res: { key: string; }) {
        // ...
        imgUrl.value = 'http://rtd5c53vw.hn-bkt.clouddn.com/' + res.key
        console.log(imgUrl.value)
        emit('fileUrl', imgUrl.value)
      }
    }
    const subscription = observable.subscribe(observer) // 上传开始
  })
}


// 限制只能上传一个文件，再次上传则覆盖之前的文件
const handleExceed: UploadProps['onExceed'] = (files) => {
  ElMessageBox.confirm('重复上传会覆盖之前的材料，是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      {
        const file = files[0] as UploadRawFile // 拿到第二次上传的文件
        const fileSize = file.size / 1024 / 1024 // 获取改文件的文件大小
        if (fileSize < 3) {
          upload.value!.clearFiles()
          file.uid = genFileId()
          upload.value!.handleStart(file)
          ElMessage.success('覆盖成功')
        } else {
          ElMessage.warning('上传文件大小不能超过 3MB!')
        }
      }
    })
    .catch(() => {
    })
}

// 校验文件上传大小，若还需校验文件格式，请自行增加代码
const handleChangeFile = (file: any, fileList: any) => {
  if (!file) return
  //限制上传文件大小
  const fileSize = file.size / 1024 / 1024
  if (fileSize > 1) {
    const currIdx = fileList.indexOf(file)
    fileList.splice(currIdx, 1)
    ElMessage.warning('上传文件大小不能超过 1MB!')
  }
}

// 提交上传
const submitUpload = () => {
  upload.value!.submit()
}
defineExpose({
  submitUpload
});
</script>

<template>
  <div class="container">
    <el-upload ref="upload" class="upload-demo" :on-exceed="handleExceed" :auto-upload="false" :action="actionUrl"
      :limit="1" :on-change="handleChangeFile" :accept="props.type == 'img' ? '.png,.jpg' : '*'"
      :http-request="uploadQiniu" name="file">
      <template #trigger>
        <el-button type="primary" class="btn-green" :icon="UploadFilled">{{ props.type == 'img' ? '上传图片' : '上传文件'
        }}</el-button>
      </template>
      <template #tip v-if="props.type == 'img'">
        <div class="el-upload__tip">
          图片格式为JPG/PNG,且大小不超过1MB
        </div>
      </template>
    </el-upload>
  </div>
</template>
